import { validateToken } from '@/utils/validateToken'
import { removeLoginInfo } from '@/utils/auth';
import store from '@/store/index.js';

const env = wx.getAccountInfoSync().miniProgram.envVersion;

const Hosts = {
  develop: 'https://wx.tongjiujiankang.com',
  trial: 'https://wx.tongjiujiankang.com',
  release: 'https://wx.tongjiujiankang.com'
}

const imgURL = 'https://tongjiujiankang.com'

const baseUrl = Hosts[env]

export { baseUrl, imgURL }

export function request(options) {

  let {
    method = 'GET',
    data = {},
    url,
    type
  } = options

  let contentType = getContentType(type)

  let headers = {
    Accept: 'application/json, text/plain, */*',
    'Content-Type': contentType 
  }
  
  // 处理 token
  let token = validateToken()
  if (token) {
    headers[token.tokenName] = token.tokenValue 
  }

  // 发起请求
  return new Promise((resolve, reject) => {
    uni.request({
      url: baseUrl + url,
      method,
      header: headers,
      timeout: 20000,//超时时间20秒
      data,
      success(res) {
        if (res.data.code == 10107) {
          uni.showToast({
            title: '登录超时，请重新登录',
            icon: 'none',
            duration: 2000
          })
          removeLoginInfo();
          store.commit('user/resetUserInfo',''); // 清空用户信息
          setTimeout(() => {
            uni.reLaunch({
              url: '/pages/login/login'
            });
          }, 2000);
        }
        resolve(res.data)
      },
      fail(err) {
        reject(err)
      }
    })
  })
}

// 获取请求头内容类型
function getContentType(type) {
  let contentType 
  switch(type) {
    case 1:
      contentType = 'application/x-www-form-urlencoded'
      break
    case 2:
      contentType = 'multipart/form-data'
      break
    default:
      contentType = 'application/json;charset=UTF-8'  
  }
  return contentType
}